class Solution:
    """
    方法：使用栈来处理括号和运算符优先级
    Args:
        s: str - 包含数字、加减号和括号的字符串表达式
    Returns:
        int - 计算后的结果
    Time: O(n) - 需要遍历整个字符串一次
    Space: O(n) - 最坏情况下栈的深度与字符串长度成正比
    """
    def calculate(self, s: str) -> int:
        res, num, sign, stack = 0, 0, 1, []
        for c in s:
            if c.isdigit():
                num = num * 10 + int(c)
            elif c in '+-':
                res += sign * num
                num = 0
                sign = 1 if c == '+' else -1
            elif c == '(':
                stack.append(res)
                stack.append(sign)
                res, sign = 0, 1
            elif c == ')':
                res += sign * num
                res *= stack.pop()
                res += stack.pop()
                num = 0
        return res + sign * num  # 处理最后的数字